package com.lanxin.xxform.controllers;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.lanxin.xxform.aspects.exceptions.ParamException;
import com.lanxin.xxform.beans.Subject;
import com.lanxin.xxform.services.SubjectService;
import com.lanxin.xxform.tools.JsonResult;

@RestController
@RequestMapping("/subject")
public class SubjectController {

    @Autowired
    private SubjectService subjectService;

    /**
     * 保存题目
     * @param subject
     * @param bindingResult
     * @return
     */
    @PostMapping("save.do")
    public JsonResult save(
        @Valid Subject subject,
        BindingResult bindingResult
    ) {
        if (bindingResult.hasErrors()) {
            FieldError fe = bindingResult.getFieldError();
            throw new ParamException(fe != null ? fe.getDefaultMessage() : "提交的数据格式错误");
        }
        return new JsonResult(subjectService.save(subject));
    }

    /**
     * 获取题目详情
     * @param id
     * @return
     */
    @GetMapping("get.do/{id}")
    public JsonResult get(@PathVariable long id) {
        return new JsonResult(subjectService.get(id));
    }

    /**
     * 统计题目数量
     * @param pid
     * @return
     */
    @PostMapping("getCount.do")
    public JsonResult getCount(
        @RequestParam(required = true) long pid
    ) {
        return new JsonResult(subjectService.getCount(pid));
    }

    /**
     * 获取题目列表
     * @param pid
     * @return
     */
    @PostMapping("getList.do")
    public JsonResult getList(
        @RequestParam(required = true) long pid
    ) {
        return new JsonResult(subjectService.getList(pid));
    }

    /**
     * 删除题目
     * @param id
     * @param uid
     * @return
     */
    @PostMapping("delete.do")
    public JsonResult delete(
        @RequestParam(required = true) long id,
        long uid
    ) {
        return new JsonResult(subjectService.delete(id, uid));
    }
    
}
